<script setup lang="ts">
import { CanvasRenderer } from "echarts/renderers";
import {
  GridComponent,
  LegendComponent,
  TooltipComponent
} from "echarts/components";
import { computed, onMounted, ref } from "vue";
import { BarChart } from "echarts/charts";
import { use, registerTheme } from "echarts/core";
import VChart from "vue-echarts";
import numeral from "numeral";
import { FlowerStatsItem } from "types/flower";
import { getFlowerStats } from "@/api/flower";

use([GridComponent, BarChart, CanvasRenderer]);

const option = ref({
  grid: {
    left: "0",
    right: "36px",
    top: "0"
  },
  xAxis: {
    type: "value"
    // show: false
  },
  yAxis: {
    type: "category",
    data: [],
    show: false
  },
  tooltip: {
    trigger: "axis",
    axisPointer: {
      type: "shadow"
    }
  },
  legend: {
    data: ["销量", "浏览量"],
    top: "bottom"
  },
  series: [
    {
      name: "销量",
      data: [],
      type: "bar",
      stack: "total",
      label: {
        show: true,
        position: "insideLeft",
        textBorderColor: "#ffffff",
        textBorderWidth: 2,
        overflow: "truncate",
        // width: 200,
        formatter: "{b}"
      },
      itemStyle: {
        color: "#41b6ff"
      }
    },
    {
      name: "浏览量",
      data: [],
      type: "bar",
      stack: "total",
      itemStyle: {
        color: "#e86033ce"
      }
    }
  ]
});

const flowerData = ref<FlowerStatsItem[]>([]);

const renderChart = async () => {
  try {
    flowerData.value = await getFlowerStats();

    const y: string[] = [];
    const x1: number[] = [];
    const x2: number[] = [];

    flowerData.value
      .sort(
        (a, b) =>
          b.sales_count + b.views_count - (a.sales_count + a.views_count)
      )
      .slice(0, 10)
      .reverse()
      .forEach(item => {
        y.push(item.name);
        x1.push(item.sales_count);
        x2.push(item.views_count);
      });

    option.value.yAxis.data = y;
    option.value.series[0].data = x1;
    option.value.series[1].data = x2;
  } catch (error) {
    console.log(error);
  }
};

onMounted(() => {
  renderChart();
});
</script>
<template>
  <el-card shadow="never">
    <div class="flex justify-between">
      <span class="text-md font-medium">热门商品</span>
    </div>
    <div class="flex justify-between items-start mt-3">
      <v-chart
        :option="option"
        autoresize
        style="width: 100%"
        :style="{ height: 50 * option.yAxis.data.length + 'px' }"
      />
    </div>
  </el-card>
</template>
